package com.ruoyi.system.service.impl;

import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.ThresholdValueMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LocalizedWarningMapper;
import com.ruoyi.system.domain.LocalizedWarning;
import com.ruoyi.system.service.ILocalizedWarningService;

/**
 * 本地预警Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-12
 */
@Service
public class LocalizedWarningServiceImpl implements ILocalizedWarningService
{
    private static final Logger log = LoggerFactory.getLogger(LocalizedWarningServiceImpl.class);

    @Autowired
    private LocalizedWarningMapper localizedWarningMapper;

    @Autowired
    private ThresholdValueMapper thresholdValueMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询本地预警
     *
     * @param id 本地预警主键
     * @return 本地预警
     */
    @Override
    public LocalizedWarning selectLocalizedWarningById(Long id)
    {
        return localizedWarningMapper.selectLocalizedWarningById(id);
    }

    /**
     * 查询本地预警列表
     *
     * @param
     * @return 本地预警
     */
    @Override
    public List<LocalizedWarning> selectLocalizedWarningList(LocalizedWarning query)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
        if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){ //注册，则代表客户
            String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
            query.setSjys(sjys);
        }
        List<LocalizedWarning> localizedWarningList = localizedWarningMapper.selectLocalizedWarningList(query);//本地化数据
        if(CollectionUtil.isNotEmpty(localizedWarningList)){
            String sampleDecWay = query.getSampleDecWay();
            if(StringUtils.isNotEmpty(sampleDecWay)){
                String type = "";
                switch (sampleDecWay){
                    case "PGTA":
                        type = "PGT-A upgarde";
                        break;
                    case "PGTAH":
                        type = "PGTAH";
                        break;
                    case "PGTSR":
                        type = "PGT-SR";
                        break;
                    case "MaReCs":
                        type = "MaReCs";
                        break;
                    case "PGTM":
                        type = "PGT-M";
                        break;
                }

                List<Integer> integerList = thresholdValueMapper.selectThresholdValueListByType(type);
                if(CollectionUtil.isNotEmpty(integerList)){ //判断是否为空，不为空，则判断
                    //遍历
                    for(LocalizedWarning localizedWarning:localizedWarningList){
                        for(Integer integer:integerList){
                            if(integer == 1 || integer == 4 || integer == 7){
                                /**
                                 * 建库方法为 ChromInst 一步成库时 :
                                 * 文库浓度需≥ 2ng/μL，若文库浓度< 2ng/μL 则标红预警
                                 */
                                String jkMethod = localizedWarning.getJkMethod();
                                Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                if(StringUtils.isNotEmpty(jkMethod) && jkMethod.equals("ChromInst一步成库") && jkwkNd < 2){
                                    localizedWarning.setJkwkNdFlag(1);
                                }
                            }else if(integer == 2 || integer == 5 || integer == 8){
                                /**
                                 * 扩增方法为两步法扩增且建库方法为酶切打断建库时 :
                                 * WGA 浓度需≥ 5ng/μL，若 WGA 浓度< 5ng/μL,标红预警；
                                 * 文库浓度需≥ 10ng/μL，若文库浓度< 10ng/μL 则标红预警
                                 */
                                String kzMethod = localizedWarning.getKzMethod();
                                String jkMethod = localizedWarning.getJkMethod();
                                if(StringUtils.isNotEmpty(kzMethod) && kzMethod.equals("两步法扩增") && StringUtils.isNotEmpty(jkMethod) && jkMethod.contains("酶切打断建库")){
                                    Double checkNd = StringUtils.isEmpty(localizedWarning.getCheckNd())?0:Double.parseDouble(localizedWarning.getCheckNd());
                                    Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                    if(checkNd < 5){
                                        localizedWarning.setCheckNdFlag(1);
                                    }
                                    if(jkwkNd < 10){
                                        localizedWarning.setJkwkNdFlag(1);
                                    }
                                }
                            }else if(integer == 3 || integer == 6 || integer == 9 || integer == 12 || integer == 15){
                                //data_QC_conclusion 为 PASS 时标绿，为 INFO 时标红
                                String dataQcConclusion = localizedWarning.getDataQcConclusion();
                                if(StringUtils.isNotEmpty(dataQcConclusion) && dataQcConclusion.equals("PASS")){
                                    localizedWarning.setDataQCconclusionFlag(2);
                                }else if(StringUtils.isNotEmpty(dataQcConclusion) && dataQcConclusion.equals("INFO")){
                                    localizedWarning.setDataQCconclusionFlag(1);
                                }
                            }else if(integer == 10){
                                /**
                                 * 建库方法为 ChromInst 一步成库时 :
                                 * 文库浓度需 ≥ 2ng/μL，若文库浓度需 < 2ng/μL 则标红预警；
                                 * 二阶段家系类型值应为非遗传型，若不符，则标红预警
                                 */
                                String jkMethod = localizedWarning.getJkMethod();
                                if(StringUtils.isNotEmpty(jkMethod) && jkMethod.equals("ChromInst一步成库")){
                                    Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                    if(jkwkNd < 2 ){
                                        localizedWarning.setJkwkNdFlag(1);
                                    }
                                    String twoJxType = localizedWarning.getTwoJxType();
                                    if(StringUtils.isEmpty(twoJxType) || !twoJxType.equals("非遗传型")){
                                        localizedWarning.setTwoJxTypeFlag(1);
                                    }
                                }

                            }else if(integer == 11){
                                /**
                                 * 扩增方法为两步法扩增且建库方法为酶切打断建库时 :
                                 * WGA 浓度需≥ 5ng/μL，若 WGA 浓度< 5ng/μL,标红预警；
                                 * 文库浓度需≥ 10ng/μL，若文库浓度< 10ng/μL 则标红预警；
                                 * 二阶段家系类型值应为遗传型，若不符，则标红预警
                                 */
                                String kzMethod = localizedWarning.getKzMethod();
                                String jkMethod = localizedWarning.getJkMethod();
                                if(StringUtils.isNotEmpty(kzMethod) && kzMethod.equals("两步法扩增") && StringUtils.isNotEmpty(jkMethod) && jkMethod.contains("酶切打断建库")){
                                    Double checkNd = StringUtils.isEmpty(localizedWarning.getCheckNd())?0:Double.parseDouble(localizedWarning.getCheckNd());
                                    Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                    if(checkNd < 5){
                                        localizedWarning.setCheckNdFlag(1);
                                    }
                                    if(jkwkNd < 10){
                                        localizedWarning.setJkwkNdFlag(1);
                                    }
                                    String twoJxType = localizedWarning.getTwoJxType();
                                    if(StringUtils.isEmpty(twoJxType) || !twoJxType.equals("遗传型")){
                                        localizedWarning.setTwoJxTypeFlag(1);
                                    }
                                }

                            }else if(integer == 13){
                                /**
                                 * 家系类型为非遗传型 or 遗传型、建库方法为 ChromInst 一步成库时 :
                                 * 文库浓度需≥ 2ng/μL，若文库浓度< 2ng/μL 则标红预警
                                 */
                                String twoJxType = localizedWarning.getTwoJxType();
                                String jkMethod = localizedWarning.getJkMethod();
                                if(StringUtils.isNotEmpty(twoJxType) && (twoJxType.equals("遗传型") || twoJxType.equals("非遗传型")) && StringUtils.isNotEmpty(jkMethod) && jkMethod.equals("ChromInst一步成库")){
                                    Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                    if(jkwkNd < 2 ){
                                        localizedWarning.setJkwkNdFlag(1);
                                    }
                                }

                            }else if(integer == 14){
                                /**
                                 * 家系类型为非遗传型 or 遗传型、扩增方法为两步法扩增且建库方法为酶切打断建库时 :
                                 * WGA 浓度需≥ 5ng/μL，若 WGA 浓度< 5ng/μL,标红预警；
                                 * 文库浓度需≥ 10ng/μL，若文库浓度< 10ng/μL 则标红预警
                                 */
                                String twoJxType = localizedWarning.getTwoJxType();
                                String jkMethod = localizedWarning.getJkMethod();
                                String kzMethod = localizedWarning.getKzMethod();
                                if(StringUtils.isNotEmpty(twoJxType) && (twoJxType.equals("遗传型") || twoJxType.equals("非遗传型")) && StringUtils.isNotEmpty(kzMethod) && kzMethod.equals("两步法扩增") && StringUtils.isNotEmpty(jkMethod) && jkMethod.contains("酶切打断建库")){
                                    Double checkNd = StringUtils.isEmpty(localizedWarning.getCheckNd())?0:Double.parseDouble(localizedWarning.getCheckNd());
                                    Double jkwkNd = StringUtils.isEmpty(localizedWarning.getJkwkNd())?0:Double.parseDouble(localizedWarning.getJkwkNd());
                                    if(checkNd < 5){
                                        localizedWarning.setCheckNdFlag(1);
                                    }
                                    if(jkwkNd < 10){
                                        localizedWarning.setJkwkNdFlag(1);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        return localizedWarningList;
    }


    public Boolean getFlag(Integer id){
        return true;
    }


    /**
     * 新增本地预警
     *
     * @param localizedWarning 本地预警
     * @return 结果
     */
    @Override
    public int insertLocalizedWarning(LocalizedWarning localizedWarning)
    {
        localizedWarning.setCreateTime(DateUtils.getNowDate());
        return localizedWarningMapper.insertLocalizedWarning(localizedWarning);
    }

    /**
     * 修改本地预警
     *
     * @param localizedWarning 本地预警
     * @return 结果
     */
    @Override
    public int updateLocalizedWarning(LocalizedWarning localizedWarning)
    {
        localizedWarning.setUpdateTime(DateUtils.getNowDate());
        return localizedWarningMapper.updateLocalizedWarning(localizedWarning);
    }

    /**
     * 批量删除本地预警
     *
     * @param ids 需要删除的本地预警主键
     * @return 结果
     */
    @Override
    public int deleteLocalizedWarningByIds(Long[] ids)
    {
        return localizedWarningMapper.deleteLocalizedWarningByIds(ids);
    }

    /**
     * 删除本地预警信息
     *
     * @param id 本地预警主键
     * @return 结果
     */
    @Override
    public int deleteLocalizedWarningById(Long id)
    {
        return localizedWarningMapper.deleteLocalizedWarningById(id);
    }

    @Override
    public List<LocalizedWarning> exportLocalizedWarningList(LocalizedWarning query) {
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
        if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){ //注册，则代表客户
            String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
            query.setSjys(sjys);
        }
        List<LocalizedWarning> localizedWarningList = localizedWarningMapper.selectLocalizedWarningList(query);//本地化数据
        return localizedWarningList;
    }

    @Override
    public String importData(List<LocalizedWarning> localizedWarningList) {
        if (StringUtils.isNull(localizedWarningList) || localizedWarningList.size() == 0)
        {
            throw new ServiceException("导入本地预警数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (LocalizedWarning localizedWarning : localizedWarningList)
        {
            String sampleId = localizedWarning.getSampleId();
            try
            {
                if(StringUtils.isEmpty(sampleId)){
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败,送检码必填";
                    failureMsg.append(msg);
                }else {
                    //获取送检码
                    String sampleBoxCode = localizedWarning.getSampleBoxCode();
                    if(StringUtils.isEmpty(sampleBoxCode)){
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败,送检码必填";
                        failureMsg.append(msg);
                    }else if(!sampleBoxCode.startsWith("ZW")) {//不以zw开头，则报错
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败,送检码 "+ sampleBoxCode +" 必须以zw开头";
                        failureMsg.append(msg);
                    } else {
                        String sjdwName = localizedWarning.getSjdwName();
                        if(StringUtils.isEmpty(sjdwName)){
                            failureNum++;
                            String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败,送检单位名称必填";
                            failureMsg.append(msg);
                        }else {
                            SysDept sysDept = new SysDept();
                            sysDept.setDelFlag("0");
                            sysDept.setDeptName(sjdwName);
                            List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(sysDept);
                            if(CollectionUtil.isEmpty(sysDeptList)){
                                failureNum++;
                                String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败,送检单位：" + sjdwName + "不存在";
                                failureMsg.append(msg);
                            }else{
                                Long id = localizedWarningMapper.getIdBySampleId(sampleId);
                                if(id != null){ //存在，则更新
                                    localizedWarning.setId(id);
                                    localizedWarningMapper.updateLocalizedWarning(localizedWarning);
                                }else{ //不存在，保存
                                    localizedWarningMapper.insertLocalizedWarning(localizedWarning);
                                }
                                successNum++;
                                successMsg.append("<br/>" + successNum + "、样本编号 " + sampleId+ " 导入成功");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、样本编号 " + sampleId + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
